package main_com.Controlers.login;


import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;


@RestController
@Slf4j
public class CaptChaController {
    String code = null;

    // 定义一个GET请求映射，路径为/captcha
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 创建一个圆形验证码对象，宽400px，高200px，字符个数4个，干扰线条数2条
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(100, 33, 4, 10);
        // 获取生成的验证码字符串
        code = captcha.getCode();
        File outputFile = new File("src/main/webapp/imgs/test.png");
        // 将验证码图片写入response的输出流中，格式为jpeg
        try {
            ImageIO.write(captcha.getImage(), "png", outputFile); // 指定要保存的文件格式
        } catch (IOException e) {
            System.err.println("Error saving image: " + e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("/captchaIsValid")
    public boolean[] codeIsValid(HttpServletRequest request, HttpServletResponse response) {
        String re = request.getParameter("code");
        return new boolean[]{code.equals(re)};
    }
}

